Secret Recipes of the Python Ninja by Cody Jackson
Author:Cody Jackson
Language: eng
Format: epub
Publisher: Packt Publishing
Published: 2018-05-21T08:59:52+00:00
How to do it...
The following examples are taken from the Python documentation at https://docs.python.org/3/library/collections.html#collections.defaultdict:
A list is a common source for default_factory, as it makes it easy to group a sequence of key:value pairs into a dictionary of lists, as follows:
>>> from collections import defaultdict
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
First, a list of tuples is created. The tuples match a string with an integer.
A defaultdict is created using an empty list as the factory argument.
The list of tuples is iterated through, assigning the tuple key:value pairs to the defaultdict list's factory.
When the sorted dictionary is printed, it shows that the defaultdict created a new key for each new item from the tuple's list. If a key was already present in the dictionary, then the tuple's value was added to the key's value as a new item in a list via the append function. Basically, the tuple's list was shorted to a key:value pairing that identified all the values related to a particular key.
Download
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Hello! Python by Anthony Briggs(9928)
OCA Java SE 8 Programmer I Certification Guide by Mala Gupta(9804)
The Mikado Method by Ola Ellnestam Daniel Brolund(9787)
Algorithms of the Intelligent Web by Haralambos Marmanis;Dmitry Babenko(8310)
Sass and Compass in Action by Wynn Netherland Nathan Weizenbaum Chris Eppstein Brandon Mathis(7792)
Test-Driven iOS Development with Swift 4 by Dominik Hauser(7772)
Grails in Action by Glen Smith Peter Ledbrook(7705)
The Well-Grounded Java Developer by Benjamin J. Evans Martijn Verburg(7567)
Windows APT Warfare by Sheng-Hao Ma(6953)
Layered Design for Ruby on Rails Applications by Vladimir Dementyev(6686)
Blueprints Visual Scripting for Unreal Engine 5 - Third Edition by Marcos Romero & Brenden Sewell(6553)
Secrets of the JavaScript Ninja by John Resig Bear Bibeault(6426)
Kotlin in Action by Dmitry Jemerov(5075)
Hands-On Full-Stack Web Development with GraphQL and React by Sebastian Grebe(4323)
Solidity Programming Essentials by Ritesh Modi(4066)
Functional Programming in JavaScript by Mantyla Dan(4044)
WordPress Plugin Development Cookbook by Yannick Lefebvre(3858)
Unity 3D Game Development by Anthony Davis & Travis Baptiste & Russell Craig & Ryan Stunkel(3800)
The Ultimate iOS Interview Playbook by Avi Tsadok(3778)
